/*
 * @Author: David Ma
 * @FilePath: \huaxia-real-estate-web\src\store\modules\user\index.ts
 * @LastEditors: David Ma
 * @Description: 该文件用于定义用户相关的store
 * @Date: 2023-05-21 10:33:15
 */
import {
  LoginData,
  RegisterData,
  getUserInfo,
  registerSendCode as sendCode,
  login as userLogin,
  logout as userLogout,
  register as userRegister,
  registerVerification as verification
} from '@/api/user';
import { clearToken } from '@/utils/auth';
import { defineStore } from "pinia";

import { UserState } from "@/store/modules/user/types";
// 创建一个名为 user 的 store
const useUserStore = defineStore('user', {
    persist: true,
    state: (): UserState => ({
        // 名字
        userName: undefined,
        // 邮箱
        userEmail: undefined,
        // 注册日期
        headUrl: undefined,
        // 账户ID
        userId: undefined,
        // 角色
        userRole: '',
    }),
    getters: {
        userInfo(state: UserState): UserState {
            return {...state};
        },
    },
// 定义 actions
    actions: {
        // 设置用户信息
       setInfo(partial: Partial<UserState>) {
            this.$patch(partial);
        },

        // 重置用户信息
        resetInfo() {
            this.$reset();
        },

        // 获取用户信息
        async info() {
            const res = await getUserInfo();

            this.setInfo(res.data);
        },

        // 登录
        async login(loginForm: LoginData) {
            try {
                return await userLogin(loginForm);
            } catch (err) {
                throw err;
            }
        },
        // 退出登录的回调函数
        logoutCallBack() {
            // const appStore = useAppStore();
            this.resetInfo();
            // 清空token
            clearToken();
        
        },
        // Logout
        async logout() {
            try {
                await userLogout();
            } finally {
                this.logoutCallBack();
            }
        },
        // 发送邮箱验证码
        async sendEmail(registerForm: RegisterData) {
            try {
                //发送验证码
                return await sendCode(registerForm)
            } catch (err) {
                throw err;
            }
        },
        // 注册
        async register(registerForm: RegisterData) {
            try {
                // 校验验证码
                const verificationRes = await verification(registerForm);
                // 如果校验通过
                if (verificationRes.data.code === 200) {
                    //进行注册
                    return await userRegister(registerForm);
                } else {
                    // 返回失败信息
                    return verificationRes;
                }
            } catch (err) {
                throw err;
            }
        }
    },
}
)
export default useUserStore;
